package com.mf.utils;

import com.mf.vo.KDJVo;
import com.mf.vo.MACD.MACDVo;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: calculateKDJ
 * Package: com.mf.utils
 * Description:
 *
 * @Author: lmf
 * @Create: 2024/5/10 14:57
 * @Version: 1.0
 */
public class CalculateKDJ {
    // 计算KDJ指标的方法
    public static List<KDJVo> getKDJ(MACDVo macdVo) {
        List<KDJVo> kdjVo = new ArrayList<>();
        double[][] kLineData = macdVo.getK();
        int period = 9;
        if (kLineData.length < 9) {
            System.out.println(macdVo.getDm()+"错误代码");
            return null;
        }

        double[] rsvArray = new double[kLineData.length]; // RSV数组
        double[] kArray = new double[kLineData.length]; // K值数组
        double[] dArray = new double[kLineData.length]; // D值数组
        double[] jArray = new double[kLineData.length]; // J值数组

        // 初始化RSV、K、D、J数组的前period-1个值为0或某个默认值
        for (int i = 0; i < period - 1; i++) {
            rsvArray[i] = 0; // 或使用某个默认值
            kArray[i] = 0;
            dArray[i] = 0;
            jArray[i] = 0;
        }

        // 计算RSV、K、D、J值
        double minPrice, maxPrice;
        for (int i = 0; i < kLineData.length; i++) {
            // for (int i = period - 1; i < kLineData.length; i++) {
            if(i < period - 1){
                kdjVo.add(new KDJVo(0.0,0.0,0.0));
            }else{
                // 计算RSV值
                minPrice = kLineData[i][2]; // 最低价
                for (int j = i - period + 1; j <= i; j++) {
                    if (kLineData[j][2] < minPrice) {
                        minPrice = kLineData[j][2];
                    }
                }
                maxPrice = kLineData[i][3]; // 最高价
                for (int j = i - period + 1; j <= i; j++) {
                    if (kLineData[j][3] > maxPrice) {
                        maxPrice = kLineData[j][3];
                    }
                }
                rsvArray[i] = (kLineData[i][1] - minPrice) / (maxPrice - minPrice) * 100;

                // 计算K值
                if (i == period - 1) {
                    kArray[i] = rsvArray[i] / 3.0; // 初始K值可以设为RSV的1/3
                } else {
                    kArray[i] = (2.0 / 3.0) * kArray[i - 1] + (1.0 / 3.0) * rsvArray[i];
                }

                // 计算D值
                if (i == period - 1) {
                    dArray[i] = kArray[i] / 3.0; // 初始D值可以设为K值的1/3
                } else {
                    dArray[i] = (2.0 / 3.0) * dArray[i - 1] + (1.0 / 3.0) * kArray[i];
                }

                // 计算J值
                jArray[i] = 3 * kArray[i] - 2 * dArray[i];
                kdjVo.add(new KDJVo(kArray[i], dArray[i], jArray[i]));
                // 将KDJ值封装成对象并添加到列表中
            }

        }
        return  kdjVo;
    }
}
